/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package forms;

import cartones.Main;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.NamingException;
import javax.swing.JOptionPane;
import megabingo.MegaBingo;
import system.Exc;
import system.Persistencia;

/**
 *
 * @author gilberto_perez
 */
public class Juego extends javax.swing.JFrame {

    private String sql = "";
    private Persistencia persistencia = new Persistencia();

    /**
     * modoJuego 0 = Estado Inicial; 1 = Bingo Carton Lleno; 2 = Filas Todas 3 =
     * Filas (solo una) 4 = Columnas Todas 5 = Columnas (solo una) Creates new
     * form Juego
     */
    public Juego() {
        initComponents();
        combo_fila.setVisible(false);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTextField1 = new javax.swing.JTextField();
        Btn_Jugar = new javax.swing.JButton();
        Btn_Limpiar = new javax.swing.JButton();
        combo_modo_juego = new javax.swing.JComboBox();
        Btn_Restaurar = new javax.swing.JButton();
        Btn_Conectar = new javax.swing.JButton();
        combo_fila = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        numero_bingo = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        detalle_bingo = new javax.swing.JTextArea();
        Btn_Reporte = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTextField1.setEnabled(false);
        jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                EnterKey(evt);
            }
        });

        Btn_Jugar.setText("Jugar");
        Btn_Jugar.setEnabled(false);
        Btn_Jugar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Btn_JugarActionPerformed(evt);
            }
        });

        Btn_Limpiar.setText("Limpiar");
        Btn_Limpiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Btn_LimpiarActionPerformed(evt);
            }
        });

        combo_modo_juego.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "--Juego--", "Bingo", "Columnas" }));
        combo_modo_juego.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                combo_modo_juegoItemStateChanged(evt);
            }
        });

        Btn_Restaurar.setText("Restaurar");
        Btn_Restaurar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Btn_RestaurarActionPerformed(evt);
            }
        });

        Btn_Conectar.setText("Conectar");
        Btn_Conectar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Btn_ConectarActionPerformed(evt);
            }
        });

        combo_fila.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Columna 1", "Columna 2", "Columna 3", "Columna 4", "Columna 5" }));

        jLabel1.setText("Bingo N°");

        numero_bingo.setToolTipText("");

        jLabel2.setText("Detalle:");

        detalle_bingo.setColumns(20);
        detalle_bingo.setRows(5);
        jScrollPane1.setViewportView(detalle_bingo);

        Btn_Reporte.setText("Reporte");

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(11, 11, 11)
                .add(jLabel1)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(numero_bingo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 20, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jLabel2)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jScrollPane1)
                .add(36, 36, 36))
            .add(layout.createSequentialGroup()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(25, 25, 25)
                        .add(combo_modo_juego, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                        .add(combo_fila, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(20, 20, 20)
                        .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 33, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                        .add(Btn_Jugar))
                    .add(layout.createSequentialGroup()
                        .addContainerGap()
                        .add(Btn_Limpiar)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(Btn_Restaurar)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(Btn_Conectar)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(Btn_Reporte)))
                .add(0, 0, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(10, 10, 10)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(combo_modo_juego, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(Btn_Jugar)
                    .add(combo_fila, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(18, 18, 18)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(Btn_Limpiar)
                    .add(Btn_Restaurar)
                    .add(Btn_Conectar)
                    .add(Btn_Reporte))
                .add(18, 18, 18)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jLabel1)
                            .add(numero_bingo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(jLabel2))
                        .add(0, 62, Short.MAX_VALUE))
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void Btn_JugarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Btn_JugarActionPerformed
        // TODO add your handling code here:

        if (Validate(jTextField1.getText())) {
            try {
                MegaBingo.balota = Integer.parseInt(jTextField1.getText());
                persistencia.dbConnect();
                sql = "INSERT INTO numeros_jugados (balota) VALUES (" + MegaBingo.balota + ")";
                persistencia.executeUpdate(sql);
                persistencia.dbDisconnect();
                MegaBingo.refrescar();
                Modo_Juego();
                Main.Main();
                jTextField1.setText("");
                jTextField1.requestFocus();
                
            } catch (Exc ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage(), "WARNING_MESSAGE", JOptionPane.ERROR_MESSAGE);
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage(), "WARNING_MESSAGE", JOptionPane.ERROR_MESSAGE);
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage(), "WARNING_MESSAGE", JOptionPane.ERROR_MESSAGE);
            }
        }

    }//GEN-LAST:event_Btn_JugarActionPerformed

    private void Btn_ConectarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Btn_ConectarActionPerformed
        try {
            // TODO add your handling code here:
            Modo_Juego();
            Main.Inicializar_Array();
            Main.Cargar_Array();
            jTextField1.setEnabled(true);
            jTextField1.requestFocus();
            Btn_Jugar.setEnabled(true);
            Btn_Conectar.setEnabled(false);
            Btn_Limpiar.setEnabled(true);
            Btn_Restaurar.setEnabled(false);
            combo_modo_juego.setEnabled(false);
            combo_fila.setEnabled(false);
        } catch (Exception ex) {
            Logger.getLogger(Juego.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_Btn_ConectarActionPerformed

    private void Btn_RestaurarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Btn_RestaurarActionPerformed
        try {
            // TODO add your handling code here:
            ResultSet rsts = null;
            Modo_Juego();
            if (MegaBingo.restaurar == false) {
                Main.Inicializar_Array();
                Main.Cargar_Array();
                MegaBingo.restaurar = false;
            }
            sql = "SELECT + FROM numeros_jugados";
            rsts = persistencia.executeRsts(sql);
            while (rsts.next()) {
                MegaBingo.balota = rsts.getInt("balota");
                Main.Main();
            }
            rsts.close();
        } catch (Exc ex) {
            Logger.getLogger(Juego.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(Juego.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NamingException ex) {
            Logger.getLogger(Juego.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(Juego.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_Btn_RestaurarActionPerformed

    private void Btn_LimpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Btn_LimpiarActionPerformed
        try {
            // TODO add your handling code here:
            MegaBingo.restaurar = false;
            for (int i = 0, len = Ventana.jTable1.getRowCount(); i < len; i++) {
                Ventana.jTable1.setValueAt(null, i, 0);
            }
            persistencia.dbConnect();
            sql = "DELETE FROM numeros_jugados";
            persistencia.executeUpdate(sql);
            persistencia.dbDisconnect();
            MegaBingo.ganadores = 0;

            sql = "SELECT setval('numeros_jugados_id_seq', 0)";
            persistencia.executeQuery(sql);

            MegaBingo.refrescar();
            jTextField1.setEnabled(false);
            Btn_Jugar.setEnabled(false);
            Btn_Limpiar.setEnabled(false);
            Btn_Restaurar.setEnabled(true);
            Btn_Conectar.setEnabled(true);
            combo_modo_juego.setEnabled(true);
            combo_fila.setEnabled(true);
        } catch (Exc ex) {
            Logger.getLogger(Juego.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(Juego.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NamingException ex) {
            Logger.getLogger(Juego.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(Juego.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_Btn_LimpiarActionPerformed

    private void combo_modo_juegoItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_combo_modo_juegoItemStateChanged
        // TODO add your handling code here:
        if (combo_modo_juego.getSelectedIndex() == 2) {
            combo_fila.setVisible(true);
        } else {
            combo_fila.setVisible(false);
        }
    }//GEN-LAST:event_combo_modo_juegoItemStateChanged

    private void EnterKey(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_EnterKey
        // TODO add your handling code here:
        if (evt.getKeyCode() == evt.VK_ENTER) {
            Btn_JugarActionPerformed(null);
        }
    }//GEN-LAST:event_EnterKey

    private void Modo_Juego() {
        MegaBingo.schema = "balota500kc";
        MegaBingo.tabla = "cartones500kc";
        if (combo_modo_juego.getSelectedIndex() == 1) {
            MegaBingo.modoJuego = 0;
        } else if (combo_modo_juego.getSelectedIndex() == 2) {
            MegaBingo.modoJuego = 1;
            switch (combo_fila.getSelectedIndex()) {
                case 0:
                    MegaBingo.FILA = 1;
                    break;
                case 1:
                    MegaBingo.FILA = 2;
                    break;
                case 2:
                    MegaBingo.FILA = 3;
                    break;
                case 3:
                    MegaBingo.FILA = 4;
                    break;
                case 4:
                    MegaBingo.FILA = 5;
                    break;
                default:
                    break;
            }
        }
    }

    private static boolean Validate(String string) {
        if (string == null || string.isEmpty()) {
            return false;
        }
        int i = 0;
        if (string.charAt(0) == '-') {
            if (string.length() > 1) {
                i++;
            } else {
                return false;
            }
        }
        for (; i < string.length(); i++) {
            if (!Character.isDigit(string.charAt(i))) {
                return false;
            }
        }
        if (Integer.parseInt(string) < 1 || Integer.parseInt(string) > 75) {
            return false;
        }
        return true;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Juego.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Juego.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Juego.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Juego.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Juego().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton Btn_Conectar;
    private javax.swing.JButton Btn_Jugar;
    private javax.swing.JButton Btn_Limpiar;
    private javax.swing.JButton Btn_Reporte;
    private javax.swing.JButton Btn_Restaurar;
    private static javax.swing.JComboBox combo_fila;
    private static javax.swing.JComboBox combo_modo_juego;
    public static javax.swing.JTextArea detalle_bingo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextField1;
    public static javax.swing.JTextField numero_bingo;
    // End of variables declaration//GEN-END:variables
}
